import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';

/// 车牌识别结果类
class PlateLprResult {
  /// 是否识别成功
  final bool success;

  /// 车牌号码
  final String? plateNumber;

  /// 识别置信度 (0.0-1.0)
  final double? confidence;

  /// 拍摄的图片路径
  final String? imagePath;

  /// 错误信息
  final String? error;

  /// 是否为无牌车 (根据plateNumber == 'noplate'判断)
  bool get isNoPlate => plateNumber == 'noplate';

  const PlateLprResult({
    required this.success,
    this.plateNumber,
    this.confidence,
    this.imagePath,
    this.error,
  });

  /// 从Map创建结果对象
  factory PlateLprResult.fromMap(Map<String, dynamic> map) {
    return PlateLprResult(
      success: map['success'] ?? false,
      plateNumber: map['plateNumber'],
      confidence: map['confidence']?.toDouble(),
      imagePath: map['imagePath'],
      error: map['error'],
    );
  }

  /// 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'success': success,
      'plateNumber': plateNumber,
      'confidence': confidence,
      'imagePath': imagePath,
      'isNoPlate': isNoPlate, // 包含getter的值
      'error': error,
    };
  }

  @override
  String toString() {
    return 'PlateLprResult{success: $success, plateNumber: $plateNumber, confidence: $confidence, imagePath: $imagePath, isNoPlate: $isNoPlate, error: $error}';
  }
}

/// 识别界面按钮类型
enum RecogButtonType {
  /// 不显示
  hidden,

  /// 显示为"无牌车"，点击返回 "noplate"
  noPlate,

  /// 显示为"手动输入"，点击返回 "input"
  manualInput,
}

/// 车牌识别配置类
class PlateLprConfig {
  /// 界面标题
  final String title;

  /// 识别按钮类型
  final RecogButtonType recogButtonType;

  const PlateLprConfig({
    this.title = '车牌识别',
    this.recogButtonType = RecogButtonType.hidden,
  });

  /// 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'title': title,
      'recogButtonType': recogButtonType.index,
    };
  }
}

/// 车牌识别插件主类
class PlateLpr {
  static const MethodChannel _channel = MethodChannel('yk.flutter.platelpr');

  /// 获取平台版本信息
  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  /// 启动车牌识别
  ///
  /// [config] 识别配置参数
  ///
  /// 返回 [PlateLprResult] 识别结果
  static Future<PlateLprResult> startRecognition({
    PlateLprConfig? config,
  }) async {
    try {
      // 检查平台支持
      if (!Platform.isAndroid) {
        return const PlateLprResult(
          success: false,
          error: '当前仅支持Android平台',
        );
      }

      // 准备参数
      final Map<String, dynamic> arguments = config?.toMap() ?? {};

      // 调用原生方法
      final dynamic result =
          await _channel.invokeMethod('startPlateLpr', arguments);

      if (result == null) {
        // 用户可能直接返回，导致结果为null
        return const PlateLprResult(success: false, plateNumber: 'back');
      }

      // 安全地转换Map类型
      final resultMap = Map<String, dynamic>.from(result as Map);

      // 解析结果
      return PlateLprResult.fromMap(resultMap);
    } on PlatformException catch (e) {
      return PlateLprResult(
        success: false,
        error: '平台调用异常: ${e.message}',
      );
    } catch (e) {
      return PlateLprResult(
        success: false,
        error: '未知错误: $e',
      );
    }
  }

  /// 快速启动车牌识别（使用默认配置）
  static Future<PlateLprResult> quickStart() async {
    return startRecognition();
  }

  /// 启动车牌识别并显示特定按钮
  static Future<PlateLprResult> startWithButtonOption({
    String title = '车牌识别',
    RecogButtonType buttonType = RecogButtonType.noPlate,
  }) async {
    return startRecognition(
      config: PlateLprConfig(
        title: title,
        recogButtonType: buttonType,
      ),
    );
  }

  /// 启动车牌识别并返回一个Map。
  /// 这是一个为旧版或特定场景设计的便利方法。
  /// 推荐使用返回[PlateLprResult]的[startRecognition]方法。
  static Future<Map<String, dynamic>?> recog({
    int recogButtonType = 0,
    String title = '车牌识别',
  }) async {
    try {
      if (!Platform.isAndroid) {
        return {
          'success': false,
          'error': '当前仅支持Android平台',
        };
      }

      final RecogButtonType buttonType;
      if (recogButtonType == 1) {
        buttonType = RecogButtonType.noPlate;
      } else if (recogButtonType == 2) {
        buttonType = RecogButtonType.manualInput;
      } else {
        buttonType = RecogButtonType.hidden;
      }

      final result = await startRecognition(
        config: PlateLprConfig(
          title: title,
          recogButtonType: buttonType,
        ),
      );

      return result.toMap();
    } catch (e) {
      return {
        'success': false,
        'error': '未知错误: $e',
      };
    }
  }

  /// 为指定的图片添加水印
  ///
  /// [imagePath] 要添加水印的图片本地路径
  /// [text] 水印文字内容，支持'\n'换行
  /// [textColor] 文字颜色
  /// [textSize] 文字大小
  /// [backgroundColor] 水印区域的背景颜色
  ///
  /// 成功时返回带水印的新图片路径，失败时抛出异常。
  static Future<String?> addWatermark({
    required String imagePath,
    required String text,
    required Color textColor,
    required double textSize,
    required Color backgroundColor,
  }) async {
    try {
      if (!Platform.isAndroid) {
        throw UnsupportedError('当前仅支持Android平台');
      }

      final String? newImagePath = await _channel.invokeMethod('addWatermark', {
        'imagePath': imagePath,
        'text': text,
        'textColor': textColor.value,
        'textSize': textSize,
        'backgroundColor': backgroundColor.value,
      });

      return newImagePath;
    } on PlatformException catch (e) {
      throw Exception('添加水印失败: ${e.message}');
    } catch (e) {
      throw Exception('添加水印时发生未知错误: $e');
    }
  }
}
